package com.java.util;

import java.io.*;

class Address implements Serializable {
    String city;

    Address(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Address{" +
                "city='" + city + '\'' +
                '}';
    }
}

class Person implements Cloneable, Serializable {
    String name;
    Address address;

    Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    // 浅拷贝
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    // 深拷贝（通过序列化/反序列化）
    public Person deepClone() throws IOException, ClassNotFoundException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(this);
            try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
                 ObjectInputStream ois = new ObjectInputStream(bis)) {
                return (Person) ois.readObject();
            }
        }
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", address=" + address +
                '}';
    }
}


/**
 * 浅拷贝：复制对象的引用和基本数据类型的值，对对象的操作会改变原对象。
 * 深拷贝：复制对象和基本数据类型的值，对对象的操作不会改变原对象。
 */
public class CopyMain {
    public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
        Address address = new Address("New York");
        Person person1 = new Person("John", address);

        // 浅拷贝
        Person person2 = (Person) person1.clone();
        person2.address.city = "Los Angeles";

        System.out.println("Person1 浅拷贝: " + person1);
        System.out.println("Person2 浅拷贝: " + person2);

        // 深拷贝
        Person person3 = new Person("John", new Address("New York")); // 原始对象
        Person person4 = person3.deepClone();
        person4.address.city = "Chicago";

        System.out.println("Person3 深拷贝: " + person3);
        System.out.println("Person4 深拷贝: " + person4);
    }
}
